<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="wave wave1"></div>
      <div class="wave wave2"></div>
      <div class="wave wave3"></div>
    </div>

    <!-- 登录表单 -->
    <div class="login-form-container">
      <div class="login-form">
        <div class="form-header">
          <div class="system-title">
            <img v-if="userStore.init_option?.config?.logo" :src="userStore.init_option?.config?.logo" alt="Logo" class="login-logo">
            <h1 v-else class="system-name">通用管理系统</h1>
          </div>
          <h2>用户登录</h2>
        </div>

        <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form-content"
          @submit.prevent="handleLogin">
          <!-- 用户名输入框 -->
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="手机号" size="large" :prefix-icon="Iphone" clearable />
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item prop="pwd">
            <el-input v-model="loginForm.pwd" type="password" placeholder="密码" size="large" :prefix-icon="Lock"
              show-password @keyup.enter="handleLogin" />
          </el-form-item>

          <!-- 移除验证码输入框，Mock模式不需要验证码 -->

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button type="primary" size="large" class="login-btn" :loading="loginLoading" @click="handleLogin">
              {{ loginLoading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <div class="copyright"> {{ config.value?.company_copyright || ''  }}
      <a href="//beian.miit.gov.cn/" target="_blank" rel="noopener noreferrer">{{ config.value?.company_icp || ''  }}</a></div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, Iphone } from '@element-plus/icons-vue'
import { login } from '@/api/auth'
import { getConfig } from '@/api/index'
import { useUserStore } from '@/stores/user'
import { forceSetupDynamicRoutes } from '@/utils/dynamicRoutes'



const router = useRouter()
const userStore = useUserStore()

// 表单引用
const loginFormRef = ref()

// 移除加密Cookie相关函数，Mock模式不需要



// 配置信息
const config = reactive({})

// 登录表单数据（移除验证码字段）
const loginForm = reactive({
  mobile: '13800138000',
  pwd: '123456'
})

// 表单验证规则（简化版，移除验证码）
const loginRules = {
  mobile: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}


/**
 * 获取配置信息
*/
const loadConfig = async () => {
  try {
    const response = await getConfig()
    const data = response.data
    config.value = data.config || {}
   // localStorage.setItem('company_name', data.config?.company_name)
    window.document.title = `登录 - `
  } catch (error) {
    console.error('获取配置信息失败:', error)
    ElMessage.error('获取配置信息失败，请刷新页面重试')
  } finally {
   
  }
}


// 加载状态
const loginLoading = ref(false)

// 移除所有验证码相关的函数

/**
 * 处理登录
 */
const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    // 表单验证
    await loginFormRef.value.validate()

    loginLoading.value = true

    // 调用Mock登录 API
    const response = await login({
      mobile: loginForm.mobile,
      pwd: loginForm.pwd
    })

    // 登录成功处理
    ElMessage.success('登录成功')

    // 简单保存登录信息到localStorage
    localStorage.setItem('login_mobile', loginForm.mobile)
    localStorage.setItem('login_pwd', loginForm.pwd)

    // 从Mock响应中获取所有数据
    const { employee_info, func_list, menu_list, init_option, notice } = response.data || {}

    // 使用 Pinia 保存用户信息
    userStore.setUserInfo({
      employee_info,    // 员工信息
      func_list,        // 功能列表
      menu_list,        // 菜单列表
      init_option,      // 初始化选项
      notice            // 公告数据
    })

    // 设置动态路由
    if (menu_list && Array.isArray(menu_list)) {
      forceSetupDynamicRoutes(menu_list)
    }

    // 跳转到首页
    router.push('/index')

  } catch (error) {
    console.error('登录失败:', error)
    if (error !== false) { // 不是表单验证错误
      // 错误消息已经在拦截器中处理了，这里不需要再次显示
    }
  } finally {
    loginLoading.value = false
  }
}

/**
 * 组件挂载时从localStorage恢复登录信息
 */
onMounted(() => {
  // 从localStorage恢复手机号和密码
  const savedMobile = localStorage.getItem('login_mobile')
  const savedPwd = localStorage.getItem('login_pwd')

  // 加载配置信息
  loadConfig()

  // 恢复保存的登录信息
  if (savedMobile) {
    loginForm.mobile = savedMobile
  }
  if (savedPwd) {
    loginForm.pwd = savedPwd
  }
})
</script>

<style scoped>
.login-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-primary-dark) 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.wave {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 6s ease-in-out infinite;
}

.wave1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  animation-delay: 0s;
}

.wave2 {
  width: 150px;
  height: 150px;
  top: 60%;
  right: 15%;
  animation-delay: 2s;
}

.wave3 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-delay: 4s;
}

@keyframes float {

  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.7;
  }

  50% {
    transform: translateY(-20px) rotate(180deg);
    opacity: 1;
  }
}

/* 登录表单容器 */
.login-form-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 480px;
  padding: 20px;
}

.login-form {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.system-title {
  margin-bottom: 20px;
}

.login-logo {
  max-height: 60px;
  max-width: 200px;
  object-fit: contain;
}

.system-name {
  color: #409EFF;
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.form-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.form-header p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.login-form-content {
  width: 100%;
}

.login-form-content .el-form-item {
  margin-bottom: 24px;
}



.captcha-item .el-form-item__content {
  display: block !important;
}

.captcha-container {
  display: flex;
  gap: 12px;
}

.captcha-container .el-input {
  flex: 1;
}

.captcha-btn {
  flex-shrink: 0;
  width: 140px;
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.copyright{
    position: fixed;
    width: 100%;
    bottom: 0;
    padding: 5px;
    left: 0;
    text-align: center;
    font-size: 12px;
    color: #fff;
    z-index: 999;
}

.copyright a{
  color: #fff;
}
</style>
